package airplane.com.example.service;

import airplane.com.example.entry.Airplane;
import airplane.com.example.entry.Ticket;
import airplane.com.example.entry.User;
import airplane.com.example.mapper.TicketMapper;
import airplane.com.example.mapper.UserMapper;
import airplane.com.example.utilities.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TicketMapper ticketMapper;

    @Override
    public Result queryUserList(User user) {
        try {
            return  new Result("查询成功!", true, userMapper.queryUserList(user));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("查询失败!", false);
        }
    }

    @Override
    public Result register(User user) {
        try {
            User queryUser = userMapper.queryUserByName(user);
            if (queryUser != null)
                return new Result("用户名已存在!", false);
            user.setId(UUID.randomUUID().toString());
            if (userMapper.insertUser(user) != 0)
                return new Result("注册成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result("系统错误：注册失败!", false);
    }

    @Override
    public Result deleteUser(User user) {
        try {
            if (userMapper.deleteUser(user) != 0) {
                ticketMapper.deleteTicketAllByUser(user);
                return new Result("删除成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result("系统错误：删除用户失败!", false);
    }

    @Override
    public Result login(User user) {
        try {
            User queryUser = userMapper.queryUserByName(user);
            if (queryUser == null)
                return new Result("不存在该用户!", false);
            if (!Objects.equals(user.getPassword(), queryUser.getPassword()))
                return new Result("密码错误!", false);
            return new Result("登录成功!", true, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("登录失败!", false);
        }
    }

    // 分页查询
    @Override
    public List<User> findByPage(Integer currentPage, Integer pageSize) {
        currentPage = (currentPage - 1) * pageSize;
        return userMapper.findByPage(currentPage, pageSize);
    }

    // 查询总页数
    @Override
    public int findTotal() {
        return userMapper.findTotal();
    }
}
